package cn.huiyunche.bms.backend.service;

import cn.huiyunche.bms.backend.bo.AdjustBO;
import cn.huiyunche.bms.backend.bo.OrderBO;
import cn.huiyunche.bms.backend.constant.AutoConfConstant;
import cn.huiyunche.bms.backend.query.SServiceOrderConditions;
import cn.huiyunche.bms.base.mapper.*;
import cn.huiyunche.bms.base.model.*;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private SOrderMapper orderMapper;
    @Autowired
    private SServiceOrderMapper serviceOrderMapper;
    @Autowired
    private AreaService areaService;
    @Autowired
    private BmsReceivableFeeDetailMapper feeDetailMapper;
    @Autowired
    private SOrderModifyLogMapper logMapper;
    @Autowired
    private SOrderViewMapper sOrderViewMapper;
    @Autowired
    private AutoConfConstant autoConfConstant;

    @Override
    public Map<String, Object> queryOrderByConditions(PageVo pageVo, SServiceOrderConditions conditions) throws Exception {
        LOGGER.info("OrderServiceImpl.queryOrderByConditions params : {}, {}", pageVo, conditions);
        Map<String, Object> map = new HashMap<>();
        String orderByClause = null;
        if (null != pageVo) {
            orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " o.id DESC";
        }

        Map<String, Object> conMap = new HashMap<>();
        conMap.put("companyId", conditions.getConsignorId());
        conMap.put("status", conditions.getStatus());
        conMap.put("departProvinceCode", conditions.getDepartProvinceCode());
        conMap.put("departCityCode", conditions.getDepartCityCode());
        conMap.put("departCountyCode", conditions.getDepartCountyCode());
        conMap.put("receiptProvinceCode", conditions.getReceiptProvinceCode());
        conMap.put("receiptCityCode", conditions.getReceiptCityCode());
        conMap.put("receiptCountyCode", conditions.getReceiptCountyCode());
        conMap.put("createTimeEnd", conditions.getCreateTimeEnd());
        conMap.put("createTimeStart", conditions.getCreateTimeStart());
        if (conditions.getOrderCodes() != null) {
            List<String> codes = Arrays.asList(conditions.getOrderCodes().split(" "));
            conMap.put("orderCodes", codes);
        }

        try {
            if (null != pageVo) {
                pageVo.setTotalRecord(orderMapper.queryOrderCountByConditions(conMap));
                conMap.put("limitStart", pageVo.getStartIndex());
                conMap.put("limitEnd", pageVo.getPageSize());
                conMap.put("orderByClause", orderByClause);
            }
            List<SOrderDetails> list = orderMapper.queryOrderByConditions(conMap);
            map.put("list", list);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.queryOrderByConditions:",e);
            throw new IllegalArgumentException("根据条件查询数据列表失败！");
        }
        try {
            List<SServiceOrderWithReceivable> cust = serviceOrderMapper.selectConsignorName();
            map.put("cust", cust);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.queryOrderByConditions:",e);
            throw new IllegalArgumentException("查询客户信息失败！");
        }
        try {
            List<BArea> areaList = areaService.queryProvince();
            map.put("areaList", areaList);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.queryOrderByConditions:",e);
            throw new IllegalArgumentException("查询区域信息失败！");
        }
        if (null != pageVo) {
            map.put("page", pageVo);
        }
        return map;
    }

    @Override
    public Integer updateCost(AdjustBO bo, BindingResult br) throws Exception {
        LOGGER.info("OrderServiceImpl.updateCost params : {}, {}", bo, br);
        if (bo.getId()==null){
            LOGGER.error("id must not be null");
            throw new IllegalArgumentException("id不能为空！");
        }else {
            BmsReceivableFeeDetailExample example = new BmsReceivableFeeDetailExample();
            example.createCriteria().andCustomerOrderIdEqualTo(bo.getId().intValue());
            List<BmsReceivableFeeDetail> list = feeDetailMapper.selectByExample(example);
            if (list.size()>0){
                throw new IllegalArgumentException("调整失败：已生成账单的订单不能修改！");
            }
        }
        SOrderModifyLog log = null;
        try {
            SOrder order = new SOrder();
            log = new SOrderModifyLog();
            order.setId(bo.getId());
            if (bo.getAftDistance() != null){
                order.setDistance(bo.getAftDistance());
                log.setModifiedDistance(bo.getAftDistance());
            }
            if (bo.getAftCost() != null){
                order.setOrderCost(bo.getAftCost());
                log.setModifiedOrderCost(bo.getAftCost());
            }
            if (!(bo.getAftCost() ==null && bo.getAftDistance() ==null))
                orderMapper.updateByPrimaryKeySelective(order);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.updateCost:",e);
            throw new IllegalArgumentException("调整订单信息失败！");
        }
        log.setOrderId(bo.getId().intValue());
        if (bo.getDistance() != null)
            log.setOldDistance(bo.getDistance());
        if (bo.getOrderCost() != null)
            log.setOldOrderCost(bo.getOrderCost());
        if (bo.getComment() != null)
            log.setComment(bo.getComment());
        if (bo.getCreateUser() != null)
            log.setCreateUser(bo.getCreateUser());
        logMapper.insertSelective(log);
        //订单放入单据池
        SServiceOrderExample example = new SServiceOrderExample();
        example.createCriteria().andCustomerOrderIdEqualTo(bo.getId());
        List<SServiceOrder> list = serviceOrderMapper.selectByExample(example);
        List<String> serviceOrders = new ArrayList<>();
        list.stream().forEach(s ->{
            serviceOrders.add(s.getOrderCode());
        });
        String strs = JSON.toJSONString(serviceOrders);
        String url = autoConfConstant.getOperation()+ "/api/waybill/addServiceOrders";
        Integer time = autoConfConstant.getOperationTime();
        Map<String, Object> map = new HashMap<>();
        map.put("serviceOrders", strs);
        String result = HttpRequestUtil.sendHttpPost(url, map, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
//            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            if (!success) {
                LOGGER.error("OrderServiceImpl addServiceOrders result error");
                throw new BusinessException(msgCode, msg);
            }else {
                LOGGER.info("OrderServiceImpl addServiceOrders result success");
            }
        }
        return null;
    }

    @Override
    public OrderBO getOrderBOById(Long id) throws Exception {
        OrderDO orderDO = sOrderViewMapper.getOrderDOById(id);
        if (!Objects.equals(orderDO, null) && !Objects.equals(orderDO, "")) {
            OrderBO bo = new OrderBO();
            BeanUtils.copyProperties(orderDO, bo);
            return bo;
        }
        return null;
    }
}
